package com.source.lightfowl.person.controller;

import com.mysql.cj.Session;
import com.source.lightfowl.VO.PersonVO;
import com.source.lightfowl.basedata.service.SlaughterHouseService;
import com.source.lightfowl.constant.SessionKey;
import com.source.lightfowl.person.entity.*;
import com.source.lightfowl.person.service.*;
import com.source.lightfowl.syslog.annotation.LogAnnotation;
import com.source.lightfowl.utils.MyResult;
import com.source.lightfowl.utils.StatusCode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;

@RestController
@CrossOrigin
@Api(tags = "用户管理")

public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private RolePlateService rolePlateService;
    @Autowired
    private UrlService urlService;
    @Autowired
    private PlateService plateService;
    @Autowired
    private SlaughterHouseService slaughterHouseService;
    @Value("${person.salt}")
    private String key;


   //用户编辑
    @ApiOperation(value = "用户编辑")
    @PostMapping("/editUser")
    public MyResult AddUser(Person person, MultipartFile file) {
        userService.addUser(person, file);
        return MyResult.build(200, "编辑成功");
    }

    @ApiOperation(value = "回显用户信息")
    @PostMapping("/findUserById")
    @ResponseBody
    public Person FindUserById(@RequestParam("id") String id){
       Person person = userService.findUserById(id);
        return person;
    }

    //分配用户角色(测试成功)
    @ApiOperation(value = "分配用户角色")
    @PostMapping("/allocateUser")
    @ResponseBody
    @Transactional
    public MyResult AllocateUser(@RequestParam("id") String id, @RequestParam("rid") String rid) {
        try {
            userService.allocateUser(rid,id);
        }catch (Exception e) {
            e.printStackTrace();
            return MyResult.build(1, "分配失败");
        }
        return MyResult.build(200, "分配成功");

    }

    //删除用户
    @ApiOperation(value = "删除用户")
    @DeleteMapping("/deleteUserById")
    @ResponseBody
    public MyResult DeleteUser(@RequestParam("id") String id) {
        try {
            userService.deleteUser(id);
        } catch (Exception e) {
            e.printStackTrace();
            return MyResult.build(1, "删除失败");
        }
        return MyResult.build(200, "删除成功");
    }

    //删除用户的角色
    @ApiOperation(value = "删除用户的角色")
    @DeleteMapping("/deleteUserRoleById")
    @ResponseBody
    public MyResult DeleteUserRole(@RequestParam String id) {
        try {
            userService.deleteUserRole(id);
        } catch (Exception e) {
            e.printStackTrace();
            return MyResult.build(1, "删除失败");
        }
        return MyResult.build(200, "删除成功");
    }

    //查询所有用户(测试通过)
    @ApiOperation(value = "查询所有用户")
    @PostMapping("/findUserAll")
    @ResponseBody
    public List<Person_Role> FindUserAll() {
        List<Person_Role> personList = userService.findUserAll();
        return personList;
    }

    @ApiOperation(value = "分页查询全部用户(未完成）")
    @GetMapping(value = "/allUser/{page}/{size}")
    public MyResult findAllUser(@PathVariable int page, @PathVariable int size){
        return null;
    }

    //条件查询用户
    @ApiOperation(value = "条件查询用户")
    @PostMapping("/findUserByName")
    @ResponseBody
    public List<Person> FindUserByLoginName(@RequestParam("Name") String Name) {
        List<Person> personList = userService.findUserByLoginName(Name);
        for (int i = 0; i < personList.size(); i++) {
            Role role = roleService.querryUserPower(personList.get(i).getRole());
            if (role!=null){
                personList.get(i).setRole(role.getRname());
            }
        }
        return personList;
    }

    //登录并确定用户权限(测试能取出权限内容)
    @ApiOperation(value = "登录并确定用户权限")
    @PostMapping(value = "/loginuser",produces = MediaType.APPLICATION_JSON_VALUE)
    @LogAnnotation(operEvent = "操作类型：用户登陆",operType = 1)
    public MyResult login(String username, String password, HttpServletRequest request) {
        HttpSession session = request.getSession();
//        if (session.getAttribute(SessionKey.USER) != null)
        Person user = null;
        if(username!=null&&password!=null&&username!=""&&password!=""){
            user =  userService.login(username,password,key);//根据用户名密码找到该用户
            /*HttpSession session = request.getSession();
            session.setAttribute("user", user);*/
        }else {
            return MyResult.build(1,"用户名或密码错误");
        }
       /* Sys_User user = new Sys_User();
        user.setRole("d387f341a85e4070a85a4eb161f169af");*/
        if (user!=null){
            if (null == user.getRole() || "".equals(user.getRole())) return MyResult.build(StatusCode.FORBIDDEN,"未赋予角色，无权登录");
            session.setAttribute(SessionKey.USER, user);
            List<PlateExtends> plateExtendsList= new ArrayList<PlateExtends>();
            //List<Url> urlList = new ArrayList<>();

            //逗号分隔的字符串转换为数组
            //获得用户所分配到的角色id
            //String[] strArray = user.getRid().split(",");//拿到rid（用户能操作的角色字符串）转化为数组
            //for(String s : strArray) {
            String rid = user.getRole();
            //获取用户所拥有的访问路径
            List<Url> urlList = urlService.findUrlsByRid(rid);
            //System.out.println(urls);
            /*for (Url url : urls) {

                //打印看看是否成功
                System.out.println(url.getUrlname());

                urlList.add(url);
            }*/
            //获得用户所拥有的访问板块
            List<Plate> plateList = plateService.querryPlate(rid);
            for (int i = 0; i < plateList.size(); i++) {
                PlateExtends plateExtends = new PlateExtends();

                //打印看看是否成功
//                System.out.println(plateList.get(i).getPname());

                plateExtends.setPlates(plateList.get(i));
                //获取用户所拥有的板块的操作
                List<Role_Plate> role_platelist = rolePlateService.querryRolePlateByPtype(plateList.get(i).getPtype(), plateList.get(i).getBigpid(), rid);
                String[] eids = new String[role_platelist.size()];
                for(int j = 0; j < role_platelist.size(); j++){
                    String eid = role_platelist.get(j).getEids();
                    eids[j] = eid;
//                    System.out.println(eid);
                }
                plateExtends.setEids(eids);
                plateExtendsList.add(plateExtends);
            }
            String houseId = slaughterHouseService.findIdByUser(user.getId());
            //}
            //通过静态工厂创建UsersExtends对象
            UsersExtends usersExtends = new UsersExtends();
            //角色拥有的路径权限
            usersExtends.setUrls(urlList);
            //角色拥有的子模块权限
            usersExtends.setPlateExtendsList(plateExtendsList);
            //浅拷贝
//            PersonVO usercopy = new PersonVO(user.getId(), user.getLoginName(), user.getPassword(), user.getName(), user.getEmail(), user.getPhone(), user.getMobile(), user.getSex(), user.getQq(), user.getWechat(), user.getWechatCode(), user.getWechatCodeDecode(), user.getIdCard());
            PersonVO usercopy = new PersonVO();
            BeanUtils.copyProperties(user, usercopy);
            /*Person user1 = new Person(user.getId(), user.getLoginName(), user.getPassword(), user.getName(),
                    user.getEmail(), user.getPhone(), user.getMobile(), user.getSex(), user.getQq(),
                    user.getWechat(), user.getWechatCode(), user.getIdCard(), user.getCreateBy(),
                    user.getStatus(), user.getCreateDate(), user.getUpdateBy(), user.getUpdateDate(),
                    user.getRole());*/
            //设置角色名
            Role role = roleService.querryUserPower(user.getRole());
            if (null == role || "".equals(role.getRname())) {
                session.removeAttribute(SessionKey.USER);
                return MyResult.build(StatusCode.FORBIDDEN,"角色关联信息无效");
            }
            String roleName = role.getRname();
            usercopy.setRoleName(roleName);
            //加入Users对象
            usersExtends.setUser(usercopy);
            usersExtends.setHouseId(houseId);
            //放入session
            session.setAttribute(SessionKey.USERSEXTENDS_SESSION_KEY, usersExtends);
//            String s=(String)request.getSession().getAttribute(username);
//            session.setAttribute("username", username);

            //需要权限控制的全部路径
//            session.setAttribute("allUrls", urlService.finAllUrls());
            return MyResult.build(200, "登录成功", usersExtends);
        }else{
            System.out.println("用户名或密码为空");
            return MyResult.build(1,"用户名或密码为空");
        }
    }

    //注销登录
    @ApiOperation(value = "注销登录")
    @PostMapping(value = "/logout")
    @ResponseBody
    @LogAnnotation(operEvent = "操作类型：用户退出登录",operType = 1)
    public MyResult logout(HttpServletRequest request) {
        HttpSession session = request.getSession();
        Object attribute = session.getAttribute(SessionKey.USERSEXTENDS_SESSION_KEY);
        if(attribute!=null) {
            session.removeAttribute(SessionKey.USER);
            session.removeAttribute(SessionKey.USERSEXTENDS_SESSION_KEY);
            return MyResult.build(200, "注销成功");
        }else {
            return MyResult.build(200, "注销失败");
        }
    }

    /**
     * 判断用户是否登录
     * @return
     */
    @ApiOperation(value = "判断用户是否登录")
    @PostMapping(value = "/getAuthority",produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public MyResult getAuthority(HttpServletRequest request) {
        HttpSession session = request.getSession();
        Object user = session.getAttribute("user");
        Object result = (user!=null)?user:"登录失败";
        return MyResult.build(1, null, result);
    }

    /**
     * 检验是否存在此用户
     * @return
     */
    @ApiOperation(value = "检验是否存在此用户")
    @PostMapping(value = "/checkUser")
    public MyResult checkUser(String username,String password) {
        Person users = userService.checkUser(username, password,key);
        String result = (users!=null)?"用户存在":"用户不存在";
        return MyResult.build(200, result);
    }

    @ApiOperation(value = "获取操作权限")
    @GetMapping(value = "/checkOprate")
    public MyResult checkOprate(String url, String username) {
        int index = url.lastIndexOf("/");
        String url_last = url.substring(index, url.length());
        List<String> eids = null;
        try {
            Person person = userService.findUser(username);
            if (person.getRole() == null) {
                return MyResult.build(1, "该用户暂未分配角色", eids);
            } else {
                eids = urlService.findOprateAuth(url_last, person.getRole());
                return MyResult.build(1, "成功", eids);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return MyResult.build(0, "获取失败");
        }

    }

    @ApiOperation(value = "获取该用户主菜单权限")
    @GetMapping(value = "/checkBp")
    public MyResult checkBigPlate(String id) {
        return MyResult.build(StatusCode.SUCCESS, "成功", userService.checkBp(id));
    }

    @ApiOperation(value = "获取该用户子菜单权限")
    @GetMapping(value = "/checkSplate")
    public MyResult checkSplate(String id, String bpid) {
        return MyResult.build(StatusCode.SUCCESS, "成功", userService.checkSplate(id, bpid));
    }



    //登录并确定用户权限
    /*
    @ApiOperation(value = "登录并确定用户权限")
    @PostMapping(value = "/login",produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody

    public UsersExtends login(String username, String password, HttpServletRequest request) {
        Person user =  userService.login(username,password,key);//根据用户名密码找到该用户
       // Sys_User user = new Sys_User();
        //user.setRole("d387f341a85e4070a85a4eb161f169af");
        List<PlateExtends> plateExtendsList= new ArrayList<PlateExtends>();
        List<Url> urlList = new ArrayList<>();
        if (user!=null){
            //逗号分隔的字符串转换为数组
            //获得用户所分配到的角色id
            String[] strArray = user.getRid().split(",");//拿到rid（用户能操作的角色字符串）转化为数组
            for(String s : strArray) {
                //获取用户所拥有的访问路径
                for (Url url : urlService.findUrlsByRid(s)) {
                    urlList.add(url);
                }
                //获得用户所拥有的访问板块
                List<Plate> plateList = plateService.querryPlate(s);
                for (int i = 0; i < plateList.size(); i++) {
                    PlateExtends plateExtends = new PlateExtends();
                    plateExtends.setPlates(plateList.get(i));
                    //获取用户所拥有的板块的操作
                    Role_Plate role_plate = rolePlateService.querryRolePlate(plateList.get(i).getPid());
                    String[] eids = role_plate.getEids().split(",");//拿到eids（用户能操作的权限字符串）转化为数组
                    plateExtends.setEids(eids);
                    plateExtendsList.add(plateExtends);
                }
            }
            //通过静态工厂创建UsersExtends对象
            UsersExtends usersExtends = new UsersExtends();
            //角色拥有的路径权限
            usersExtends.setUrls(urlList);
            //角色拥有的子模块权限
            usersExtends.setPlateExtendsList(plateExtendsList);

            //加入Users对象
            usersExtends.setUsers(user);
            HttpSession session = request.getSession();
            session.setAttribute("user", usersExtends);
            String s=(String)request.getSession().getAttribute(username);
            session.setAttribute("username", username);

            //需要权限控制的全部路径
            session.setAttribute("allUrls", urlService.finAllUrls());
            return usersExtends;
        }else{
            return null;
        }
    }

    */

    /*//查询用户角色权限
    @PostMapping("/findUserPower")
    @ResponseBody
    public List<RoleAll> FindUser(@RequestParam("loginName") String loginName) {
       Sys_User sys_user = userService.findUser(loginName);
        Role role = roleService.querryUserPower(sys_user.getRole());
        List<RoleAll> roleAllList = new LinkedList<>();

        List<Role_Plate> role_plateList = rolePlateService.querryRolePlate(sys_user.getRole());
        try {
            for (int j = 0; j < role_plateList.size(); j++) {
                //封装RoleAll
                RoleAll roleAll = new RoleAll();
                roleAll.setRid(sys_user.getRole());
                roleAll.setRname(role.getRname());
                roleAll.setEids(role_plateList.get(j).getEids());
                Plate plate = plateService.querryPlate(role_plateList.get(j).getPid());
                roleAll.setPname(plate.getPname());
                Big_Plate big_plate = plateService.querryBigPlate(plate.getBigpid());
                roleAll.setBpname(big_plate.getBpname());
                roleAllList.add(roleAll);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return roleAllList;
    }*/
}
